package com.example.hms.service.serviceImpl;
import com.example.hms.Dao.RoomDao;
import com.example.hms.entity.Room;
import com.example.hms.service.RoomService;
import com.example.hms.ulit.Result;
import com.example.hms.ulit.ResultSubmit;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@Service
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
public class RoomServiceImpl implements RoomService {
    @Resource
    RoomDao roomDao;
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Override
    public Result selectAll(String roomNumber,String roomTypeName,String roomId) {
        List<Room> rooms = roomDao.selectAll(roomNumber,roomTypeName,roomId);
        return ResultSubmit.success(rooms);
    }


    @Override
    public Result insert(Room room) {
        room.setDataUpdateTime(format.format(new Date()));
        room.setRoomId(Math.abs((int)System.currentTimeMillis()));
        room.setDeleteIdentity("未删除");
        int insert=roomDao.insert(room);
        if (insert!=0){
            return ResultSubmit.success("添加成功");
        }else {
            // 事务回滚(手动回滚)
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultSubmit.error("添加失败");
        }
    }

    @Override
    public Result update(Room room) {
        int update1 = roomDao.update(room);
        room.setDataUpdateTime(format.format(new Date()));

        room.setRoomId(Math.abs((int)System.currentTimeMillis()));
        room.setDeleteIdentity("未删除");
        int insert1 = roomDao.insert(room);
        if (update1==1 || insert1==1){
            return ResultSubmit.success("修改成功");
        }else {
            // 事务回滚(手动回滚)
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultSubmit.error("修改失败");
        }
    }

    @Override
    public Result delete(Room room){
        int delete1 = roomDao.update(room);
        if (delete1==1){
            return ResultSubmit.success("执行成功");
        }else {
            // 事务回滚(手动回滚)
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultSubmit.error("执行失败");
        }
    }
}
